<?php

namespace App\Service\Cruise\Mission;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseOrderInputModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Support\CustomForm\AttributeCruiseSupport;

class CruiseTourInputService extends CruiseOrderInputBaseService
{
    private ?CruiseOrderModel $cruiseOrderModel;
    private ?CruiseCheckDetailModel $cruiseCheckDetailModel;
    private int               $userId;
    private int               $shopId;

    public function __construct(int $cruiseOrderId, int $shopId = 0, int $userId = 0)
    {
        $this->shopId = $shopId;
        $this->userId = $userId;

        $this->cruiseOrderModel = CruiseOrderModel::query()->where('id', $cruiseOrderId)->first();
        if (!$this->cruiseOrderModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的云巡店任务ID:{$cruiseOrderId}");
        }

        $this->cruiseCheckDetailModel = CruiseCheckDetailModel::getDataByOrderId($this->cruiseOrderModel->id);
        if (!$this->cruiseCheckDetailModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '未初始化cruiseCheckDetail信息');
        }

        parent::__construct($cruiseOrderId, $this->cruiseOrderModel->type, $this->cruiseOrderModel->cruiseTemplateRel->sysTemplate ?? 0);
    }

    /**
     * 初始化表单信息
     * @param bool $forceUpdate
     * @param int $templateId
     * @return void
     */
    public function initOrderInput(bool $forceUpdate = false, int $templateId = 0): void
    {
        if (!$templateId) {
            $templateId = CruiseTemplateModel::query()
                    ->where('type', CruiseTemplateModel::TYPE_6)
                    ->where('sysTemplate', CruiseTemplateModel::SYS_TEMPLATE_TOUR)
                    ->where('status', CruiseTemplateModel::STATUS_ON)
                    ->value('id') ?? 0;
            if (!$templateId) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "获取模板类型对应模板失败:{$this->templateType}");
            }
        }

        // 幂等-不再创建
        if (!$forceUpdate && CruiseOrderInputModel::query()->where('orderId', $this->orderId)->where('templateType', $this->templateType)->count()) {
            return;
        }

        parent::baseInitOrderInput($templateId);
    }

    /**
     * 保存用户填写内容
     * @param string $field
     * @param $value
     * @param array $auditValue
     */
    public function saveUserContentJson(string $field, $value, array $auditValue = []): void
    {
        // 状态校验
        if (!in_array(
            $this->cruiseOrderModel->status,
            [CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_NOT_MODIFY]
        )) {
            $statusText = CruiseOrderModel::CRUISE_STATUS_MAPPING[$this->cruiseOrderModel->status] ?? '';
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前状态: {$statusText}，不允许修改");
        }

        parent::baseSaveUserContentJson($field, $value, $auditValue);
    }


    /**
     * 获得表单信息
     * @return array
     */
    public function getInputObjectFill(): array
    {
        return parent::baseGetInputObjectFill(false);
    }

    /**
     * 巡检任务记录提交
     */
    public function submitOrder(): void
    {
        // 状态校验
        if (!in_array(
            $this->cruiseOrderModel->status,
            [CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_NOT_MODIFY]
        )) {
            $statusText = CruiseOrderModel::CRUISE_STATUS_MAPPING[$this->cruiseOrderModel->status] ?? $this->cruiseOrderModel->status;
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "任务状态错误，当前状态:" . $statusText);
        }

        // 角色校验
        if ($this->userId != $this->cruiseOrderModel->handlerId) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "您无权操作，当前处理人：{$this->cruiseOrderModel->handlerId}");
        }

        parent::baseSubmitOrder(true);

        // 提交后干的事
        $inputs        = (new CheckInputService($this->cruiseOrderModel->id, $this->userId))
            ->getInputObjectFill()['lists'];
        $signatureImgs = [];
        $totalNum      = $failNum = 0;
        $actualScore   = $totalScore = 0;

        foreach ($inputs as $input) {
            foreach ($input['projects'] as $i) {
                switch ($i['inputType']){
                    case AttributeCruiseSupport::INPUT_TYPE_SIGNATURE:
                    case AttributeCruiseSupport::INPUT_TYPE_PAYEE_INFO:
                        $signatureImgs = $i['value'] ?? [];
                        break;
                    case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK:
                        $totalNum++;
                        $options = collect($i['customAttributes']['options'])->sortByDesc('score')->keyBy('value');
                        // 不合格
                        if ($i['value'] == 2) {
                            $failNum++;
                        } elseif ($i['value'] == 1) {
                            $actualScore += ($options[$i['value']]['score'] ?? 0);
                        }

                        $totalScore += ($options->first()['score']);
                        break;
                    case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP:
                    case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_BIOLOGY:

                        $totalNum++;
                        $options = collect($i['customAttributes']['options'])->sortByDesc('score')->keyBy('value');
                        // 不合格
                        if ($i['value'] == 2) {
                            $failNum++;
                        } elseif ($i['value'] == 1) {
                            $actualScore += ($options[$i['value']]['score'] ?? 0);
                        } elseif ($i['value'] == 3) {

                            // 不适用
                            break;
                        }

                        $totalScore += ($options->first()['score']);

                        break;
                }
            }
        }

        $successScore = floor($totalScore * 0.6);

        $this->cruiseOrderModel->status = CruiseOrderModel::STATUS_NOT_REVIEW;
        $this->cruiseOrderModel->save();

        $this->cruiseCheckDetailModel->failNum      = $failNum;
        $this->cruiseCheckDetailModel->totalScore   = $totalScore;
        $this->cruiseCheckDetailModel->successScore = $successScore;
        $this->cruiseCheckDetailModel->actualScore  = $actualScore;
        $this->cruiseCheckDetailModel->submitTime   = time();
        $this->cruiseCheckDetailModel->isSignature  = $signatureImgs ? 1 : 0;
        $this->cruiseCheckDetailModel->totalNum     = $totalNum;
        $this->cruiseCheckDetailModel->createdByUid = $this->userId;

        $this->cruiseCheckDetailModel->reportResult = $this->cruiseCheckDetailModel->actualScore > $this->cruiseCheckDetailModel->successScore ? CruiseCheckDetailModel::REPORT_RESULT_QUALIFIED : CruiseCheckDetailModel::REPORT_RESULT_UNQUALIFIED;

        $this->cruiseCheckDetailModel->save();

        // process
        CruiseOrderProcessModel::query()->create([
            'cruiseOrderId' => $this->cruiseOrderModel->id,
            'step'          => CruiseOrderProcessModel::PROCESS_SUBMITTED,
            'status'        => CruiseOrderProcessModel::STATUS_OK,
            'type'          => $this->cruiseOrderModel->type,
        ]);

        // 通知对应审核人员
    }

    public function audit(array $data): void
    {
        // TODO: Implement audit() method.
    }
}
